<template>
	<view class="pay_box">
		<view class="header_bg"></view>
		<view class="menu">
			<view class="info">
				<view class="user">
					<image :src="mer.mer_avatar" mode=""></image>
					<view class="right">
						<view>{{mer.mer_name}}</view>
						<text></text>
					</view>
				</view>
				<view class="main">
					<view class="xf_a">
						<view class="title">支付金额</view>
					</view>
					<view class="xf_a">
						<text>￥</text>
						<view class="money">
							<input @input="mo_inp" type="digit" value="" placeholder-style="font-size: 40rpx;" placeholder="询问服务员后输入" v-model="money"/>
						</view>
					</view>
				</view>
				<!-- <view class="main">
					<view class="xf_a">
						<view class="title">支付方式</view>
					</view>
					<view class="payItem acea-row row-middle" v-if="count_money <= user.now_money">
						<view class='name acea-row row-center-wrapper'>
							<view class='iconfont animated icon-icon-test bounceIn'></view>
							<view class="title">余额支付</view>
							<checkbox-group @change="changeYue" >
								<checkbox value="all" :checked="checkYue"/>
							</checkbox-group>
						</view>
					</view>
					<view class="payItem acea-row row-middle">
						<view class='name acea-row row-center-wrapper'>
							<view class='iconfont animated icon-weixin2'></view>
							<view class="title">微信支付</view>
							<checkbox-group @change="changeWeixin" >
								<checkbox value="all" :checked="checkWeixin"/>
							</checkbox-group>
						</view>
					</view>
					<view class="xf_a">
						<view class="title"></view>
					</view>
				</view>
				 -->
				<view class='wrapper'>
					<view class='item'>
						<view>支付方式</view>
						<view class='list'>
							<!-- #ifdef H5 -->
							<view class='payItem acea-row row-middle' :class='active==index ?"on":""' @tap='payItem(index)' v-for="(item,index) in cartArr"
							 :key='index' v-if="item.payStatus==1">
								<view class='name acea-row row-center-wrapper'>
									<view class='iconfont animated' :class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'></view>{{item.name}}
								</view>
								<view class='tip'>
									{{item.title}}
									<block v-if="item.value == 'balance'">
										{{user.now_money}}
									</block>
								</view>
							</view>
							<!-- #endif -->
							<!-- #ifdef MP || APP-PLUS -->
							<view class='payItem acea-row row-middle' :class='active==index ?"on":""' @tap='payItem(index)' v-for="(item,index) in cartArr"
							 :key='index' v-if="item.payStatus==1">
								<view class='name acea-row row-center-wrapper'>
									<view class='iconfont animated' :class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'></view>{{item.name}}
								</view>
								<view class='tip'>
									{{item.title}}
									<block v-if="item.value == 'balance'">
										{{user.now_money}}
									</block>
								</view>
							</view>
							<!-- #endif -->
						</view>
					</view>
				</view>
				<view class="zj" v-if="redpack_money>0">
					<view>红包抵扣</view>
					<text>-￥{{redpack_money}}</text>
				</view>
				<view class="zj" v-if="dis_money>0">
					<view>折扣优惠</view>
					<text>-￥{{dis_money}}</text>
				</view>
				<view class="zj">
					<view>总计</view>
					<text>￥{{count_money}}</text>
				</view>
			</view>
			<view class="pay_btn" @tap="send_pay">买单{{order_money==0?'':count_money+'元'}}</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<official-account class="official-account"></official-account>
		<!-- #endif -->
		<view class="alipaysubmit" v-html="formContent"></view>
		<!-- #ifdef MP -->
		<authorize @onLoadFun="onLoadFun" :isGoIndex="isGoIndex" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
		<!-- #endif -->
	</view>
</template>

<script>
	let app = getApp();
	import {
		qrpayCheckOrder,
		qrpayCreateOrder
	} from '@/api/qrpay.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	import {
		WX_AUTH,
		STATE_KEY,
		LOGINTYPE,
		BACK_URL
	} from '@/config/cache';
	import store from '@/store';
	import Cache from '@/utils/cache';
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	export default {
		components: {
			// #ifdef MP
			authorize
			// #endif
		},
		computed: mapGetters(['isLogin']),
		data() {
			return {
				mer_id: 0,
				app_id: '',
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				isGoIndex: false,
				showMV:false,//是否显示文字 元
				p_ltext:'',
				money: '',// 支付金额
				order_money:0,//支付金额
				dis_money:0,//折扣优惠金额
				count_money:0,//支付金额
				mer: {},
				user:{
					now_money:0
				},
				formContent: '',
				checkYue: true,
				checkWeixin: false,
				payType:'weixin',
				from: '',
				active: 0, //支付方式切换
				cartArr: [{
						"name": "微信支付",
						"icon": "icon-weixin2",
						value: 'weixin',
						title: '微信快捷支付',
						payStatus: 1,
					},	
					{
						name: "支付宝支付",
						icon: "icon-zhifubao",
						// #ifdef H5		
						value: 'alipay',
						// #endif
						// #ifdef MP
						value: 'alipayQr',
						// #endif
						title: '支付宝支付',
						// #ifdef H5
						payStatus: app.globalData.alipay_open,
						// #endif
						// #ifdef MP
						payStatus: 2
						// #endif
					},
					{
						"name": "余额支付",
						"icon": "icon-icon-test",
						value: 'balance',
						title: '可用余额:',
						payStatus: app.globalData.yue_pay_status,
					},
				],
			};
		},
		onReady() {			
			uni.$on('update',(data)=>{
				// #ifdef H5
				this.cartArr[1]['payStatus'] = this.$wechat.isWeixin()?2:data.alipay_open
				// #endif
				this.cartArr[2]['payStatus'] = data.alipay_open
			})
		},
		mounted: function() {		
			this.$nextTick(() => {
				const app = getApp();
				// #ifdef H5
				this.cartArr[1]['payStatus'] = this.$wechat.isWeixin()?2:app.globalData.alipay_open
				// #endif
				this.cartArr[2]['payStatus'] = app.globalData.yue_pay_status
			});
			
		},
		onLoad(options) {
			this.mer_id = options.mer_id || 0;
			if(this.mer_id == 0){
				let q = options.q || '';
				q = decodeURIComponent(q);
				let mer_id = this.getQueryString(q, 'mer_id');
				console.log('mer_id:'+mer_id)
				this.mer_id = mer_id;
			}
			if(this.mer_id == 0){
				this.$util.Tips({
					title: '参数错误',
					icon: 'none'
				});	
				return;
			}
			// #ifdef H5
			this.from = this.$wechat.isWeixin() ? 'weixin' : 'h5'
			// #endif
			// #ifdef MP
			this.from = 'routine'
			// #endif
			if (this.isLogin  == false) {
				// #ifdef H5 || APP-PLUS
				toLogin();
				// #endif 
				// #ifdef MP
				this.isAuto = true;
				this.$set(this, 'isShowAuth', true)
				// #endif
			}else{
				console.log('checkOrder');
				this.checkOrder();
			}
			if (this.payType == 'weixin') {
				this.payType = this.from
			}
		},
		methods:{
			payItem: function(e) {
				let that = this;
				let active = e;
				that.active = active;
				that.animated = true;
				that.payType = that.cartArr[active].value;
				if (that.payType == 'weixin') {
					that.payType = that.from
				}
			},
			changeYue:function(){
				this.checkYue = true
				this.checkWeixin = false
			},
			changeWeixin:function(){
				this.checkYue = false
				this.checkWeixin = true
			},
			getQueryString:function(url, key) { 
				var str = url.split("?")[1],items=str.split("&");
				var arr,name,value;
				for(var i = 0, l = items.length; i < l; i++){
				    arr=items[i].split("=");
				    name= arr[0];
					value= arr[1];
					if(name == key){
						return value;
					}
				}
				return 0;
			},
			// 授权回调
			onLoadFun() {
				this
				this.checkOrder();
			},
			// 授权关闭
			authColse: function(e) {
				console.log('authColse:'+e)
				if(e)
					this.isShowAuth = e
				else{
					this.isShowAuth = e
					this.checkOrder();
				}
			},	
			checkOrder: function() {
				let that = this;
				qrpayCheckOrder(that.mer_id).then(res => {
					that.mer = res.data;
					that.user = res.data.user;
					that.showMV = false
					that.money = '';
					that.order_money = 0;
					that.dis_money = 0;
					that.count_money = 0;
				}).catch(function (error) {
					if(error.status == 40000){
						// #ifdef H5 || APP-PLUS
							toLogin();
						// #endif 
						// #ifdef MP
						that.isAuto = true;
						that.$set(that, 'isShowAuth', true)
						// #endif
					}else{
						return that.$util.Tips({
							title: error.message,
							icon: 'none'
						});	
					}
					// alert(JSON.stringify(error))
				    //这里只会在接口是失败状态返回，不需要去处理错误提示
				    console.log(error);
				});
			},
			qrpayCreateOrder: function(pay_money,no_money,mark) {
				let that = this;
				qrpayCreateOrder(this.mer_id, that.payType,pay_money,no_money,mark).then(res => {
						// alert(JSON.stringify(res))
						let status = res.data.status,
						orderId = res.data.result.order_id,
						callback_key = res.data.result.pay_key,
						jsConfig = res.data.result.config,
						goPages = '/pages/qrcode/pay_sure?order_id=' + orderId + '&msg=' + res.message;
						
						switch (status) {
							case 'ORDER_EXIST':
							case 'EXTEND_ORDER':
							case 'PAY_ERROR':
							case 'error':
								uni.hideLoading();
								return that.$util.Tips({
									title: res.msg
								}, {
									tab: 5
								});
								that.checkOrder();
								break;
							case 'success':
								uni.hideLoading();
								return that.$util.Tips({
									title: res.msg,
									icon: 'success'
								}, {
									tab: 5,
									url: goPages
								});
								break;
							case 'alipay':
							case "alipayQr":
								uni.hideLoading();
								this.$emit('onChangeFun', {
									action: 'payClose'
								});
								uni.navigateTo({
									url: '/pages/order_pay_back/index?keyCode='+callback_key+'&url='+jsConfig
								})
								return;
								break;
								// #ifndef MP
							case "wechat":
							case "weixin":						
								jsConfig.timeStamp = jsConfig.timestamp;
								this.$wechat.pay(jsConfig).then(res => {
									console.log('测试支付数据无效的success：' + res.data)
									return that.$util.Tips({
										title: res.message,
										icon: 'success'
									}, {
										tab: 4,
										url: goPages
									});
								}).catch(res => {
									console.log('测试支付数据无效的catch：' + res.data)
									that.checkOrder();
									if (res.errMsg == 'chooseWXPay:cancel') {
										return that.$util.Tips({
											title: '取消支付'
										});
									}
								})
								break;
								// #endif
								// #ifdef MP
							case "routine":
								jsConfig.timeStamp = jsConfig.timestamp;
								that.toPay = true;
								uni.requestPayment({
									...jsConfig,
									success: function(res) {
										uni.hideLoading();
										return that.$util.Tips({
											title: '支付成功',
											icon: 'success'
										}, {
											tab: 5,
											url: goPages
										});
									},
									fail: function(e) {
										uni.hideLoading();
										that.checkOrder();
										return that.$util.Tips({
											title: '取消支付'
										});
									},
								})
								break;
								// #endif
							case "balance":
								uni.hideLoading();
								//余额不足
								return that.$util.Tips({
									title: res.msg
								}, {
									tab: 5,
									url: goPages + '&status=1'
								});
								break;
								// #ifdef H5
							case 'h5':
								let host = window.location.protocol + "//" + window.location.host;
								let url = `${host}/pages/qrcode/pay_sure?order_id=${orderId}`
								let eUrl = encodeURIComponent(url)
								let locations = `${jsConfig.mweb_url}&redirect_url=${eUrl}`
								setTimeout(() => {
									location.href = locations;
								}, 100);
								break;
								// #endif		
						}
						
						// uni.hideLoading();
						// if(status=='error'){
						// 	return that.$util.Tips({
						// 		title: '支付失败',
						// 		icon: 'none'
						// 	}, {
						// 		tab: 5,
						// 		url: goPages
						// 	});	
						// }
						// if(!jsConfig){
						// 	return that.$util.Tips({
						// 		title: '支付成功',
						// 		icon: 'success'
						// 	}, {
						// 		tab: 5,
						// 		url: goPages
						// 	});
						// }
						// // #ifdef MP-WEIXIN
						// jsConfig.timeStamp = jsConfig.timestamp;
						// uni.requestPayment({
						// 	...jsConfig,
						// 	success: function(res) {
						// 		uni.hideLoading();
						// 		if (that.BargainId || that.combinationId || that.pinkId || that.seckillId)
						// 			return that.$util.Tips({
						// 				title: '支付成功',
						// 				icon: 'success'
						// 			}, {
						// 				tab: 4,
						// 				url: goPages
						// 			});
						// 		return that.$util.Tips({
						// 			title: '支付成功',
						// 			icon: 'success'
						// 		}, {
						// 			tab: 5,
						// 			url: goPages
						// 		});
						// 	},
						// 	fail: function(e) {
						// 		uni.hideLoading();
						// 		return that.$util.Tips({
						// 			title: '取消支付',
						// 				icon: 'none'
						// 		});
						// 		that.checkOrder();
						// 	},
						// 	complete: function(e) {
						// 		uni.hideLoading();
						// 		//关闭当前页面跳转至订单状态
						// 		if (res.errMsg == 'requestPayment:cancel') 
						// 			return that.$util.Tips({
						// 				title: '取消支付',
						// 				icon: 'none'
						// 			});
						// 		that.checkOrder();
						// 	},
						// })
						// // #endif
						// // #ifdef H5
						// 	// that.formContent = jsConfig;
						// 	// that.$nextTick(() => {
						// 	// 	document.getElementById('alipaysubmit').submit();
						// 	// })
						// // #endif
						
				}).catch(function (error) {
					alert(error)
				    //这里只会在接口是失败状态返回，不需要去处理错误提示
				    console.log(error);
				});
			},
			// 金额输入
			mo_inp:function(res){
				console.log('money:'+res.detail.value)
				if(res.detail.value!=''){
					if (res.detail.value.indexOf(".") < 0 && res.detail.value != "") {
						res.detail.value = parseFloat(res.detail.value);
						console.log('1-'+res.detail.value)
						this.money = res.detail.value;
					} else if (res.detail.value.indexOf(".") == 0) {
						console.log('首位小数点情况')
						res.detail.value = res.detail.value.replace(/[^$#$]/g, "0.");
						res.detail.value = res.detail.value.replace(/\.{2,}/g, ".");
						this.money = res.detail.value;
						console.log('2-'+res.detail.value)	
					}else if(!(/^(\d?)+(\.\d{0,2})?$/.test(res.detail.value))){
					          //去掉最后一位
						res.detail.value = res.detail.value.substring(0, res.detail.value.length - 1)
						console.log('3-'+res.detail.value)	
						this.$nextTick(() => {
							this.money = res.detail.value;
						})
					}
				}else{
					this.money = ''
				}
				this.computeMoney()
			},
			computeMoney:function(){
				this.order_money = parseFloat(this.money).toFixed(2);
				console.log('消费金额：'+this.order_money)
				if(this.order_money > 0){
					this.showMV=true
					console.log('用户红包：'+this.user.now_money)
					this.mer.qrpay_user_rate = this.mer.qrpay_user_rate??100
					this.dis_money = parseFloat(this.order_money*1*(100-this.mer.qrpay_user_rate)/100).toFixed(2)
					if(this.dis_money*1 < 0){
						this.dis_money = 0;
					}
					this.count_money = parseFloat(this.order_money*1-this.dis_money*1).toFixed(2);
					
					console.log('折扣金额：'+this.dis_money)
					console.log('支付金额：'+this.count_money)
					if(this.count_money > this.user.now_money){
						if(this.payType == 'balance'){
							this.payType = this.from
						}
						this.cartArr[2]['payStatus'] = 2
					}else{
						this.cartArr[2]['payStatus'] = app.globalData.yue_pay_status
					}
				}else{
					this.showMV=false
					this.order_money = 0;
					this.count_money=0
					this.dis_money = 0;
				}
				console.log('用户红包：'+this.user.now_money)
				if(this.order_money*1<0.01){
					this.showMV=false
					this.order_money = 0;
					this.count_money=0
					this.dis_money = 0;
					return;
				}
			},
			// 发起支付
			send_pay:function(){
				var that=this
				if(that.money==''){
					uni.showToast({
						icon:'none',
						title:'请输入付款金额'
					})
					return false;
				}
				uni.showLoading({
					title: '订单支付中',
					mask:true
				});
				that.qrpayCreateOrder(this.money,this.no_money,this.p_ltext);
			},
			getPay:function(){
				var that=this
				uni.showLoading({
					title:'发起支付中...'
				})
				setTimeout(function(){
					uni.hideLoading()
					uni.showToast({
						icon:'success',
						title:'支付成功',
						success() {
							setTimeout(function(){
								uni.navigateTo({
									url:'./pay_sure?money='+that.money
								})
							},1500)
						}
					})
				},2500)
			},
		}
		
	}
</script>

<style lang="less">
	.alipaysubmit {
		display: none;
	}
	page{
		background:  #f5f5f5;
	}
	.pay_box{
		.header_bg{
			width: 100%;
			height: 85rpx;
			background:  #e93323;
		}
		.menu{
			width: 690rpx;
			margin: 0 auto;
			
			margin-top: -65rpx;
			.info{
				border-radius: 12rpx;
				overflow: hidden;
				background: #f7f7f7;
				border-radius: 12rpx;
				margin-bottom: 55rpx;
				.user{
					background: #fff;
					box-sizing: border-box;
					padding: 30rpx 35rpx;
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					image{
						width: 90rpx;
						height: 90rpx;
						margin-right: 30rpx;
					}
					.right{
						view{
							font-size: 28rpx;
							color: #333;
							margin-bottom: 25rpx;
						}
						text{
							font-size: 24rpx;
							color: #999;
						}
					}
				}
				.main{
					background: #fff;
					box-sizing: border-box;
					padding: 0 30rpx;
					margin-bottom: 25rpx;
					.xf_a{
						display: flex;
						align-items: center;
						box-sizing: border-box;
						justify-content: space-between;
						padding: 30rpx 0rpx;
						// border-bottom: 1rpx solid #eee;
						.money text{
							font-size: 28rpx;
							color: #333;
							padding-left: 6rpx;
						}
						.money{
							width: 100%;
							display: flex;
							align-items: left;
							justify-content: left;
							padding-left: 20rpx;
							font-size: 40rpx;
							color: #000;
							input{
								font-size: 40rpx;
								color: #333;
							}
						}
						.title{
							font-size: 26rpx;
							color: #333;
						}
					}
					.hb{
						display: flex;
						align-items: center;
						box-sizing: border-box;
						justify-content: space-between;
						padding: 27rpx 0rpx;
						border-bottom: 1rpx solid #eee;
						view{
							font-size: 26rpx;
							color: #333;
							text{
								color: #e93323;
							}
						}
						image{
							border-radius: 50%;
							width: 35rpx;
							height: 35rpx;
						}
					}
					.beihzu{
						display: flex;
						align-items: center;
						box-sizing: border-box;
						justify-content: space-between;
						padding: 27rpx 0rpx;
						view{
							font-size: 26rpx;
							color: #333;
						}
						input{
							color: #333;
							text-align: right;
							font-size: 28rpx;
						}
					}
				}
				.zj{
					display: flex;
					align-items: center;
					justify-content: space-between;
					box-sizing: border-box;
					padding: 35rpx 30rpx;
					position: relative;
					background: #fff;
					view{
						font-size: 28rpx;
						font-weight: 600;
					}
					text{
						font-size: 28rpx;
						font-weight: 600;
					}
				}
			}
			.pay_btn{
				width: 100%;
				border-radius: 8rpx;
				height: 90rpx;
				line-height:90rpx;
				text-align: center;
				font-size: 30rpx;
				color: #fff;
				background: #e93323;
			}
		}
	}
	.official-account{
		position: absolute;
		bottom: 0rpx;
		width: 100%;
	}
	
	
	.payItem {
		border-bottom: 1px solid #eee;
		// border-radius: 6rpx;
		height: 86rpx;
		width: 100%;
		box-sizing: border-box;
		margin: 10rpx 0;
		font-size: 28rpx;
		color: #282828;
	}
	
	.payItem.on {
		border-color: #fc5445;
		color: #e93323;
	}
	
	.payItem .name {
		width: 100%;
		text-align: center;
		// border-right: 1px solid #eee;
		justify-content: left;
		padding-left: 0rpx;
	}
	
	.payItem .name .iconfont {
		width: 44rpx;
		height: 44rpx;
		border-radius: 50%;
		text-align: center;
		line-height: 44rpx;
		background-color: #fe960f;
		color: #fff;
		font-size: 30rpx;
		margin-right: 15rpx;
	}
	
	.payItem .name .iconfont.icon-weixin2 {
		background-color: #41b035;
	}
	
	.payItem .name .iconfont.icon-zhifubao {
		background-color: #4295D5;
	}
	
	.payItem .name .title{
		width: 500rpx;
		text-align: left;
	}
	
	.payItem .name checkbox-group{
		width: 60rpx;
		display: flex;
		align-items: flex-end;
		justify-content: flex-end;
	}
	
	
	.wrapper {
		margin-bottom: 12rpx;
		background-color: #fff;
	}
	
	.wrapper .item {
		padding: 27rpx 30rpx;
		font-size: 30rpx;
		color: #282828;
	}
	
	.wrapper .item .discount {
		font-size: 30rpx;
		color: #999;
	
		&.discount_voice {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			width: 500rpx;
			text-align: right;
		}
	}
	
	.wrapper .item .discount .iconfont {
		color: #515151;
		font-size: 30rpx;
		margin-left: 15rpx;
	}
	
	.wrapper .item .discount .num {
		font-size: 32rpx;
		margin-right: 20rpx;
	}
	
	.wrapper .item .shipping {
		font-size: 30rpx;
		color: #999;
		position: relative;
		padding-right: 58rpx;
	}
	
	.wrapper .item .shipping .iconfont {
		font-size: 35rpx;
		color: #707070;
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		margin-left: 30rpx;
	}
	
	.wrapper .item input {
		display: flex;
		flex: 1;
		height: 100%;
		margin-left: 20rpx;
	}
	
	.wrapper .item .placeholder {
		color: #ccc;
	}
	
	.wrapper .item .list {
		margin-top: 35rpx;
	}
	
	.wrapper .item .list .payItem {
		border: 1px solid #eee;
		border-radius: 6rpx;
		height: 86rpx;
		width: 100%;
		box-sizing: border-box;
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #282828;
	}
	
	.wrapper .item .list .payItem.on {
		border-color: #fc5445;
		color: #e93323;
	}
	
	.wrapper .item .list .payItem .name {
		width: 50%;
		text-align: center;
		border-right: 1px solid #eee;
		justify-content: left;
		padding-left: 80rpx;
	}
	
	.wrapper .item .list .payItem .name .iconfont {
		width: 44rpx;
		height: 44rpx;
		border-radius: 50%;
		text-align: center;
		line-height: 44rpx;
		background-color: #fe960f;
		color: #fff;
		font-size: 30rpx;
		margin-right: 15rpx;
	}
	
	.wrapper .item .list .payItem .name .iconfont.icon-weixin2 {
		background-color: #41b035;
	}
	
	.wrapper .item .list .payItem .name .iconfont.icon-zhifubao {
		background-color: #4295D5;
	}
	
	.wrapper .item .list .payItem .tip {
		width: 49%;
		text-align: center;
		font-size: 26rpx;
		color: #aaa;
	}
</style>